let mysql = require('mysql');
let to = require('./await-to-js');
let fs = require('fs');
let path = require('path');

//数据库操作类
class DB {
    constructor({
        host = 'localhost',
        user = 'root',
        password = 'root',
        database = 'xiaou',
        port = '3306'
    } = {}) {
        //链接对象
        this.conn = null;
        //配置对象
        this.dbConfig = {
            host,
            user,
            password,
            database,
            port
        };
    }
    //创建链接
    connect() {
        return new Promise((resolve, reject) => {
            this.conn = mysql.createConnection(this.dbConfig);
            //和数据库建立链接
            this.conn.connect(err => {
                err ? reject(err) : resolve('1');
            });
        });
    }
    //执行操作方法
    //sql 要执行的SQL语句
    //parmas  参数 sql中占位符对应的数据
    async query(sql, params = []) {
        let [err, data] = await to(this.connect());//创建链接
        if (err) {    //创建链接失败
            throw '错误';
        }
        let p = new Promise((resolve, reject) => {
            //执行数据库操作
            this.conn.query(sql, params, (err, result) => {
                err ? reject(err) : resolve(result);
            });
        });
        return p;
    }
    //关闭数据库
    close() {
        this.conn.end();
    }
}


//读取数据库配置文件
let buf = fs.readFileSync(path.join(__dirname, 'config.json'));
let obj = JSON.parse(buf.toString());//将配置文件转换为对象
let db = new DB(obj);

// new DB().connect().then()
// xx.query();
// new DB().query();

module.exports = db;